package akaram.util;

import java.util.Random;

/**
 * 
 * This class generate random dice rolls.
 * 
 * @author johan.paz
 *
 */
public class DiceRoller 
{
	private static Random rnd = new Random();
	
	public static int rollADice( int faces )
	{
		return rnd.nextInt(faces) + 1;
	}
	
	public static int rollDice( int number, int faces, int plus )
	{
		int resul = plus;
		
		for( int i = 0; i < number; i ++ )
		{
			resul += rollADice(faces);
		}
		
		return resul;
	}
	
	/**
	 * 
	 * Roll a group of dices in the sintax: NdF+P or P+NdF or NdF-P
	 * 
	 * @param dice
	 * @return
	 * @throws RollDiceException 
	 */
	public static int rollDice( String dice ) throws RollDiceException
	{
		int resul = 0;
		int plus = 0;
		int number = 0;
		int faces = 0;
		
		// Supressing spaces
		dice = dice.replaceAll(" ", "");
		
		String[] pp = dice.split("[dD]");
		
		if ( pp.length != 2 )
			throw new RollDiceException("No 'd' in the roll expression.");
		
		String[] pp0 = pp[0].split("[+-]");
		
		if ( pp0.length == 2 )
		{
			plus = Integer.parseInt(pp0[0]);
			number = Integer.parseInt(pp0[1]);
			faces = Integer.parseInt(pp[1]);
		}
		else
		{
			String[] pp1 = pp[1].split("[+-]");
			
			if ( pp1.length == 2 )
			{
				number = Integer.parseInt(pp[0]);
				faces = Integer.parseInt(pp1[0]);
				plus = Integer.parseInt(pp1[1]);
			}
			else
			{
				number = Integer.parseInt(pp[0]);
				faces = Integer.parseInt(pp[1]);
			}
		}
		
		return rollDice(number, faces, plus);
	}
	
	public static void main( String[] params )
	{
		for( String str: params )
		{
			try {
				System.out.println("D" + str + " = " + rollDice(str) );
			} catch (RollDiceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
